package com.square.service.common.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : wangsu
 * @date : 2021/11/17 10:41
 * @description : 请求参数解析器
 */
public class RequestAnalyUtil {

    /**
     * 获取请求参数
     *
     * @param request
     * @return
     */
    public static Map<String, String> getParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }


    /**
     * 获取json参数
     *
     * @param request
     * @return
     */
    public static String getJsonParam(HttpServletRequest request) throws Exception {
        request.setCharacterEncoding(CharsetUtil.UTF_8);
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String jsonStr;
        StringBuilder param = new StringBuilder();
        try {
            while ((jsonStr = reader.readLine()) != null) {
                param.append(jsonStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        reader.close();
        if (StrUtil.isBlank(param)) {
            return null;
        }
        return param.toString();
    }

}
